#include "Codec.h"
#include <endian.h>
#include <fstream>

#include <muduo/base/Logging.h>

void Codec::decode()
{
    uint32_t content1_size_net = *static_cast<const uint32_t*>((const void*)(initStr_.data()));
    uint32_t content1_size_host = be32toh(content1_size_net);
    retStrDecodeContent1_.assign(initStr_.begin() + sizeof(uint32_t),
                                 initStr_.begin() + sizeof(uint32_t) + content1_size_host);
    
    uint32_t content2_size_net = *static_cast<const uint32_t*>((const void*)(initStr_.data() + sizeof(uint32_t) + content1_size_host));
    uint32_t content2_size_host = be32toh(content2_size_net);
    retStrDecodeContent2_.assign(initStr_.begin() + 2 * sizeof(uint32_t) + content1_size_host,
                                 initStr_.begin() + 2 * sizeof(uint32_t) + content1_size_host + content2_size_host);
}

void Codec::encode(const std::string& fileName)
{
    uint32_t retSize = getFileSize(fileName);
    assert (retSize > 0);

    uint32_t t = htobe32(retSize);
    retStrEncode_.assign(static_cast<char*>((void*)(&t)), sizeof(uint32_t));

    std::ifstream retImage(fileName);
    char buf[retSize + 1];
    retImage.read(buf, retSize);
    retStrEncode_ += std::string(buf, retSize);
}

uint32_t Codec::getFileSize(const std::string& fileName)
{
    std::ifstream in(fileName);
    in.seekg(0, std::ios::end);
    if (!in.is_open())
    {
        LOG_INFO << "Codec::getFIleSize(): open file failed";
        return 0;
    }
    uint32_t size = in.tellg();
    in.close();
    
    return size;
}